//
//  PKPlayViewController.m
//  AMomentApp
//
//  Created by lanou on 15/10/6.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "PKPlayViewController.h"
#import "PKHeaderView.h"
#import "PKPlayMusicView.h"
#import "PKRequestManager.h"
#import "PKPlayerManager.h"
#import "PKPlayListTableViewController.h"
#import "PKRadioPlayViewController.h"
#import "PKRadioHostViewController.h"
#import "UMSocial.h"
@interface PKPlayViewController () <UIScrollViewDelegate,UMSocialUIDelegate>

@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) PKPlayMusicView *playMusicView;
@property (nonatomic, strong) PKPlayListTableViewController *listTableViewControl;
@property (nonatomic, strong) PKRadioPlayViewController *radioPlayControl;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) PKRadioHostViewController *hostViewControl;


@property (nonatomic, strong) PKPlayModel *radioModel;
@property (nonatomic, strong) NSMutableArray *hostArray;

@end

@implementation PKPlayViewController

-(NSMutableArray *)musicURLArray
{
    if (_musicURLArray == nil) {
        self.musicURLArray = [NSMutableArray array];
    }
    return _musicURLArray;
}

-(PKPlayModel *)radioModel
{
    if (_radioModel == nil) {
        self.radioModel = [[PKPlayModel alloc]init];
    }
    return _radioModel;
}

-(NSMutableArray *)hostArray
{
    if (_hostArray == nil) {
        self.hostArray = [NSMutableArray array];
    }
    return _hostArray;
}

// 网络请求数据
- (void)configureData
{
    NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:self.tingId,@"tingid",@"63A94D37-33F9-40FF-9EBB-481182338873",@"deviceid", nil];
    NSLog(@"%@",self.tingId);
    [PKRequestManager PKRequestManagerrequsetWithType:POST URLString:@"http://api2.pianke.me/ting/info" ParDIc:parDic finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        [self.radioModel setValuesForKeysWithDictionary:dic[@"data"]];
        for (NSDictionary *hostDic in dic[@"data"][@"moreting"]) {
            PKRadioDetailModel *hostModel = [[PKRadioDetailModel alloc]init];
            [hostModel setValuesForKeysWithDictionary:hostDic];
            [self.hostArray addObject:hostModel];
        }
        [self updateData];

    } error:^(NSError *error) {
        NSLog(@"%@",[error localizedDescription]);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self configureData];
    
    PKHeaderView *headerView = [[PKHeaderView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 50)];
    [headerView.leftButton setImage:[UIImage imageNamed:@"arrow"] forState:UIControlStateNormal];
    [headerView.leftButton addTarget:self action:@selector(getBackPKRadioMainDetailControl:) forControlEvents:UIControlEventTouchUpInside];
    [headerView.shareButton addTarget:self action:@selector(shareRadioForOtherPerson:) forControlEvents:UIControlEventTouchUpInside];
    [headerView.collectionButton addTarget:self action:@selector(collectionRadioForMyself:) forControlEvents:UIControlEventTouchUpInside];
    [headerView.timeButton addTarget:self action:@selector(timeing:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:headerView];
    
    // *************** 外部最大的ScrollView ********
    _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 70, SCREEN_WIDTH, SCREEN_HEIGHT -140)];
    _mainScrollView.contentSize = CGSizeMake(SCREEN_WIDTH*4, SCREEN_HEIGHT- 140);
    _mainScrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    _mainScrollView.pagingEnabled = YES;
    _mainScrollView.delegate = self;
    _mainScrollView.showsHorizontalScrollIndicator = NO;
    
    PKPlayerManager *manager = [PKPlayerManager sharedManager];
    [manager setManagerMusicArray:self.musicURLArray];
    [manager playWithIndex:self.index];
    
    // ********* 底部的音乐播放器界面 ****************
    _playMusicView = [[PKPlayMusicView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-70, SCREEN_WIDTH, 140)];
    _playMusicView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_playMusicView];
    
    [self showAllViewControl];
    
    // 播放器的按钮点击事件
    [self.playMusicView.beforeButton addTarget:self action:@selector(playBeforeMusic:) forControlEvents:UIControlEventTouchUpInside];
    [self.playMusicView.nextButton addTarget:self action:@selector(playnextMusic:) forControlEvents:UIControlEventTouchUpInside];

    [self.playMusicView.playButton addTarget:self action:@selector(playAndPanseMusic:) forControlEvents:UIControlEventTouchUpInside];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeIndexPathForMusic:) name:@"changeIndexPath" object:@"changeIndex"];
    // Do any additional setup after loading the view.
}

//******************* 音乐播放器 ***************
- (void)playBeforeMusic:(UIButton *)button
{
    [[PKPlayerManager sharedManager]beforeMusic];
    ((PKRadioDetailModel *)self.dataSourceArray[self.index]).isSelected = NO;
    if (self.index == 0) {
        self.index = self.dataSourceArray.count - 1;
    }else
    {
        _index--;
    }
    ((PKRadioDetailModel *)self.dataSourceArray[self.index]).isSelected = YES;
    _tingId = ((PKRadioDetailModel *)self.dataSourceArray[self.index]).tingid;
    [self configureData];
}

- (void)playnextMusic:(UIButton *)button
{
    [[PKPlayerManager sharedManager]nextMusic];
    ((PKRadioDetailModel *)self.dataSourceArray[self.index]).isSelected = NO;
    if (self.index == self.dataSourceArray.count) {
        _index = 0;
    }else
    {
        self.index++;
    }
    ((PKRadioDetailModel *)self.dataSourceArray[self.index]).isSelected = YES;
    _tingId = ((PKRadioDetailModel *)self.dataSourceArray[self.index]).tingid;
    [self configureData];
}

- (void)playAndPanseMusic:(UIButton *)button
{
    _playMusicView.playButton.selected = !_playMusicView.playButton.selected;
    [[PKPlayerManager sharedManager]playAndPause];
    if (_playMusicView.playButton.state == UIControlStateSelected) {
        _playMusicView.playButton.selected = !_playMusicView.playButton.selected;
    }
}

// 当点击tableView的下标时 改变所有界面展示的数据
- (void)changeIndexPathForMusic:(NSNotification *)Notification
{
    self.index = [[Notification.userInfo objectForKey:@"index"] integerValue];
    _tingId = ((PKRadioDetailModel *)self.dataSourceArray[self.index]).tingid;
    [[PKPlayerManager sharedManager]playWithIndex:self.index];
    [self configureData];
}

// 加载所有视图控制器的界面
- (void)showAllViewControl
{
    _listTableViewControl = [[PKPlayListTableViewController alloc]init];
    _listTableViewControl.dataArray = self.dataSourceArray;
    _listTableViewControl.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-140);
    [_mainScrollView addSubview:_listTableViewControl.tableView];
    
    _radioPlayControl = [[PKRadioPlayViewController alloc]init];
    _radioPlayControl.radioPlayModel = self.radioModel;
    _radioPlayControl.mArray = self.musicURLArray;
    _radioPlayControl.row = self.index;
    _radioPlayControl.view.frame = CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT-140);
    [_mainScrollView addSubview:_radioPlayControl.view];
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*2, 0,SCREEN_WIDTH , SCREEN_HEIGHT-140)];
    _webView.backgroundColor = [UIColor whiteColor];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:((PKPlayModel *)self.dataSourceArray[self.index]).playInfo.webview_url]];
    [_webView loadRequest:request];
    [_mainScrollView addSubview:_webView];
    
    [self.view addSubview:_mainScrollView];
    
    _hostViewControl = [[PKRadioHostViewController alloc]init];
    _hostViewControl.hostInfoMdeol = self.radioModel;
    _hostViewControl.hostArray = self.hostArray;
    
    __weak PKPlayViewController *playVC = self;
    _hostViewControl.moreWorkBlock = ^(NSString *str){
        _tingId = str;
        for (int i = 0; i < self.dataSourceArray.count; i++) {
            PKRadioDetailModel *Model = playVC.dataSourceArray[i];
            if (Model.tingid == _tingId) {
                playVC.index = i;
            }
        }
        [playVC configureData];
        playVC.mainScrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    };
    _hostViewControl.view.frame = CGRectMake(SCREEN_WIDTH*3, 0, SCREEN_WIDTH, SCREEN_HEIGHT-140);
    [_mainScrollView addSubview:_hostViewControl.view];
    
}

// 刷新数据
- (void)updateData
{
    [_listTableViewControl UPDateData:self.dataSourceArray];
    [_radioPlayControl UPdateData:_radioModel];
    [_hostViewControl UPdateData:_radioModel array:self.hostArray];
    _hostViewControl.hostArray = self.hostArray;
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:((PKPlayModel *)self.dataSourceArray[self.index]).playInfo.webview_url]]];
}


// 收藏
- (void)collectionRadioForMyself:(UIButton *)button
{
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:nil message:@"你还没登录哦" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
    [alertControl addAction:action];
    [self presentViewController:alertControl animated:YES completion:nil];
}

// 分享
- (void)shareRadioForOtherPerson:(UIButton *)button
{
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"561c5f76e0f55ab642001b90" shareText:nil shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToRenren,UMShareToSina,UMShareToTencent, nil] delegate:self];
}

- (void)timeing:(UIButton *)button
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [formatter stringFromDate:date];
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:dateStr delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _playMusicView.pageControl.currentPage = _mainScrollView.contentOffset.x / SCREEN_WIDTH;
}

- (void)getBackPKRadioMainDetailControl:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
